<template>
  <div class="setting">
    <el-card class="box-card">
      <el-tabs v-model="activeName">
        <el-tab-pane label="角色管理" name="first">
          <el-button
            style="margin:40px auto;"
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="showDialog = true"
            v-if="checkPoint('POINT-USER-ADD')"
            >新增角色</el-button
          >
          <el-table :data="tableData" border style="width: 100%">
            <el-table-column type="index" label="序号" width="180">
            </el-table-column>
            <el-table-column prop="name" label="角色名" width="180">
            </el-table-column>
            <el-table-column prop="description" label="描述"> </el-table-column>
            <el-table-column label="操作" width="180">
              <!-- 插槽：表单每一行的元素内容默认只能写文字 -->
              <template slot-scope="{ row }">
                <el-link @click="assignPermission(row.id)" type="primary"
                  >分配权限</el-link
                >
                <el-link
                  @click="editRole(row.id)"
                  style="margin:0 10px"
                  type="primary"
                  >修改</el-link
                >
                <el-link
                  @click="doDel(row.id)"
                  type="primary"
                  v-if="checkPoint('point-user-delete')"
                  >删除</el-link
                >
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page.sync="pageInfo.page"
            :page-size="pageInfo.pagesize"
            layout="total, prev, pager, next"
            :total="pageInfo.total"
            style="text-align:center"
            @current-change="getRoleList"
          >
            <!-- current-change点击当前页 -->
          </el-pagination>
        </el-tab-pane>
        <el-tab-pane :model="companyForm" label="公司信息" name="second">
          <!-- 表单 -->
          <el-form style="width:450px;margin:0 auto;" label-width="80px">
            <el-form-item label="企业名称">
              <el-input v-model="companyForm.name" disabled></el-input>
            </el-form-item>
            <el-form-item label="公司地址">
              <el-input
                v-model="companyForm.companyAddress"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="公司电话">
              <el-input v-model="companyForm.companyPhone" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="companyForm.mailbox" disabled></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="companyForm.remarks" disabled></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <!-- 弹出框：表格的修改按钮 -->
      <el-dialog @close="cancel" :title="title" :visible.sync="showDialog">
        <el-form
          ref="addForm"
          :model="addForm"
          label-width="100px"
          :rules="addRules"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="addForm.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="region">
            <el-input v-model="addForm.region" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="saveRole">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 弹出框：表格的权限分配按钮 -->
      <el-dialog
        @click="cancelPermission"
        title="分配权限"
        :visible.sync="showPermDialog"
        width="30%"
      >
        <!-- default-checked-keys	默认勾选的节点的 key 的数组 -->

        <!-- getCheckedKeys	若节点可被选择（即 show-checkbox 为 true），则返回目前被选中的节点的 key 所组成的数组 -->
        <!-- check-strictly 选中时父子节点互补关联 -->
        <el-tree
          ref="permissionTree"
          check-strictly
          :data="treeData"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="checkedKeys"
          :props="defaultProps"
        >
        </el-tree>
        <el-row style="margin-top:20px" type="flex" justify="center">
          <el-button @click="assign" size="small" type="primary"
            >确 定</el-button
          >
          <el-button @click="cancelPermission" size="small">取 消</el-button>
        </el-row>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  getRoleList,
  deleteRole,
  addRole,
  getRoleDetail,
  editRole,
  getCompanyInfo,
  assignPermisson
} from '@/api/settings'
// 权限列表
import { getPermissionList } from '@/api/permission'
// 工具函数
import { getDepData } from '@/utils'
export default {
  name: 'setting',
  data () {
    return {
      // 默认勾选的节点数组
      checkedKeys: [],
      // 当前点击的角色id
      currentId: '',
      // 分配权限弹出框
      treeData: [
        {
          id: 1,
          label: '一级 1',
          children: [
            {
              id: 4,
              label: '二级 1-1',
              children: [
                {
                  id: 9,
                  label: '三级 1-1-1'
                },
                {
                  id: 10,
                  label: '三级 1-1-2'
                }
              ]
            }
          ]
        },
        {
          id: 2,
          label: '一级 2',
          children: [
            {
              id: 5,
              label: '二级 2-1'
            },
            {
              id: 6,
              label: '二级 2-2'
            }
          ]
        },
        {
          id: 3,
          label: '一级 3',
          children: [
            {
              id: 7,
              label: '二级 3-1'
            },
            {
              id: 8,
              label: '二级 3-2'
            }
          ]
        }
      ],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 分配权限
      showPermDialog: false,
      activeName: 'first',
      tableData: [],
      // 页码数据
      pageInfo: {
        total: 10,
        page: 1,
        pagesize: 5
      },
      // 新增表单数据
      addForm: {},
      showDialog: false,
      // 验证规则：
      addRules: {
        name: [{ required: true, trigger: 'blur', message: '请输入角色名称' }],
        // name: [{ required: true, message: "请输入角色名", trigger: "blur" }],
        region: [{ required: true, trigger: 'blur', message: '请输入角色描述' }]
      },
      // 公司信息
      companyForm: {}
    }
  },
  created () {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    // 分配权限的点击事件
    async assignPermission (id) {
      this.showPermDialog = true
      // 获取权限列表
      let res = await getPermissionList()
      // console.log(res)
      this.treeData = getDepData(res.data, '0')
      // 把被点的角色id存起来
      this.currentId = id
      // 获取当前被选中的角色权限详情
      let res2 = await getRoleDetail(id)
      // console.log(res2)
      this.checkedKeys = res2.data.permIds
    },

    // 分配权限的确认按钮
    async assign () {
      // getCheckedKeys	若节点可被选择（即 show-checkbox 为 true），则返回目前被选中的节点的 key 所组成的数组
      let ids = this.$refs.permissionTree.getCheckedKeys()
      let res = await assignPermisson({
        id: this.currentId,
        permIds: ids
      })
      console.log(res)
      this.$message('成功给角色分配权限！')
      // this.showPermDialog = false
      // 不用重新加载页面所有数据
      // 每次重新修改权限时都要先清空上一次的修改记录！
      this.cancelPermission()
    },

    // 权限分配的取消按钮
    cancelPermission () {
      this.showPermDialog = false
      this.treeData = []
      this.checkedKeys = []
    },

    // 根据id1查询企业信息
    async getCompanyInfo () {
      let res = await getCompanyInfo(this.companyId)
      // console.log(res)
      this.companyForm = res.data
    },
    async getRoleList () {
      let res = await getRoleList(this.pageInfo)
      // console.log(res)
      this.tableData = res.data.rows
      this.pageInfo.total = res.data.total
    },
    async doDel (id) {
      // 删除按钮
      // 弹出提示框：确认/取消删除
      try {
        // $confirm返回的是一个promise对象！
        await this.$confirm('确认删除吗？')
        await deleteRole(id)
        this.$message.success('删除成功')
        this.getRoleList()
      } catch (error) {}
    },

    // 新增

    // 新增的确认按钮：
    saveRole () {
      // 整个表单的验证、发送请求新增
      this.$refs.addForm.validate(async value => {
        // 验证通过
        if (value) {
          if (this.addForm.id) {
            await editRole(this.addForm)
          } else {
            let res = await addRole(this.addForm)
            // console.log(res)
          }
          this.$message.success(this.title + '成功')
          this.showDialog = false
          this.getRoleList()
        }
      })
    },
    // 新增：取消按钮
    cancel () {
      // 清空表单
      this.addForm = {}
      // 清空验证规则
      this.$refs.addForm.resetFields()
      // 隐藏对话框
      this.showDialog = false
    },
    // id：识别点击的是哪个要修改
    async editRole (id) {
      this.showDialog = true
      // 获取角色详细信息
      let res = await getRoleDetail(id)
      console.log(res)
      // 表单内容=获取到的后台数据
      this.addForm = res.data
    }
  },
  computed: {
    ...mapGetters(['companyId']),

    title () {
      return this.addForm.id ? '编辑角色' : '新增角色'
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep {
  .setting {
    .box-card {
      margin: 20px;
    }
  }
}
</style>
